<template>
  <div class="app-container">
    <help :show-help="showHelp" />
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width: 120px"
        clearable
        class="filter-item"
        @change="handleFilter"
        @clear="clearStatus"
      >
        <el-option
          v-for="item in statusMap"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="listQuery.id"
        placeholder="ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="会员ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
    >
      <el-table-column
        width="50"
      />
      <el-table-column sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="凭证" align="center" width="120">
        <template slot-scope="{row}">
          <el-image
            v-if="row.images && row.images[0] && row.images[0].image"
            style="width: 100px; height: 100px"
            :src="row.images[0].image.path"
            :preview-src-list="[...row.images.map(x => x.image.path)]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="任务" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.task">{{ row.task.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员" align="center" width="80">
        <template slot-scope="{row}">
          <div class="demo-image__lazy" v-if="row.user">
            <el-image :src="row.user.avatar" lazy style="border-radius: 50%">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div>ID: {{row.user.id}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="昵称">
        <template slot-scope="{row}">
          <span v-if="row.user">{{ row.user.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话">
        <template slot-scope="{row}">
          <span v-if="row.user">{{ row.user.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="status" label="状态" width="100">
        <template slot-scope="{row}">
          <span style="color: red">{{ row.status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column label="奖金" width="100">
        <template slot-scope="{row}">
          <span style="color: red" v-if="row.task">{{ +row.task.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="驳回" width="100">
        <template slot-scope="{row}">
          <span style="color: red">{{ row.reject }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="240"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button v-if="+row.status !== 3" type="primary" size="mini" icon="el-icon-edit" @click="handleCheck(row)">
            发放奖金
          </el-button>
          <el-button v-if="+row.status !== 3 && +row.status !== 4" type="danger" size="mini" icon="el-icon-delete" @click="handleReject(row)">
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
    <el-dialog
      title="请填写原因:"
      :visible.sync="dialogVisible"
      width="30%">
      <span>
        <el-input v-model="reject" placeholder="原因说明" />
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveReject()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
import Help from './components/Help'
import config from '@/config'

const initQuery = {
  status: config.taskCheck.CHECK,
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'TaskCheck',
  components: {
    Pagination,
    Help
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.taskCheck.statusText(+status)
    }
  },
  data() {
    return {
      // 状态
      status: {},
      // 状态
      statusMap: [],
      // 显示帮助提示
      showHelp: false,
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {},
      selectionList: [],
      // 显示控制
      // listShow: {
      //   id: true,
      //   date: true,
      //   image: true
      // }
      dialogVisible: false,
      reject: '',
      current_id: 0
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getStatusList()
    this.getList()
  },
  methods: {
    handleCheck(row) {
      this.$confirm('您确定要通过审核吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.taskCheck.check({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '操作成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.status = this.status.FINISH
              // this.$set(x, 'status', this.status.FINISH)
            }
          })
          // 删除掉
          this.list = this.list.filter(x => +x.status !== this.status.FINISH)
        })
      }).catch(() => {})
    },
    handleReject(row) {
      this.current_id = row.id
      this.reject = ''
      this.dialogVisible = true
    },
    saveReject() {
      this.$confirm('您确定要驳回吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogVisible = false
        api.taskCheck.reject({ id: this.current_id, reject: this.reject }).then(response => {
          this.$message({
            message: response.message || '操作成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === this.current_id) {
              x.status = this.status.REJECT
            }
          })
          // 删除掉
          this.list = this.list.filter(x => +x.status !== this.status.REJECT)
        })
      }).catch(() => {})
    },
    /**
     * 清除状态
     */
    clearStatus() {
      // this.listQuery.status = config.news.ALL
      this.listQuery.status = null
    },
    /**
     * 获取状态列表
     */
    getStatusList() {
      this.listLoading = true
      api.taskCheck.statusList().then(response => {
        const { data } = response
        this.statusMap = data
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      // 状态需要处理
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      api.taskCheck.list({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
        // this.list.forEach(x => {
        //   // 搜索高亮
        //   x.titleWrapper = this.wrapperKeyword('title', x.title)
        //   // 状态处理
        //   const statusForm = +x.status === this.status.OPEN
        //   this.$set(x, 'statusForm', statusForm)
        // })
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/task/check',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      this.status = config.taskCheck
    },
    /**
     * 查询高亮
     */
    wrapperKeyword(k, v) {
      const highlight = value => {
        return `<span style="color: #1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      }
      return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>
